package com.fish.service.impl.passport;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fish.passport.dao.PassCodeDAO;
import com.fish.passport.dao.PassPortCodeDAO;
import com.fish.passport.po.PassCode;
import com.fish.passport.po.PassPortCode;
import com.fish.passport.processor.OrderPerformProcessor;
import com.fish.passport.processor.ProcessorFactory;
import com.fish.passport.processor.UsedCodeProcessor;
import com.fish.service.passport.OrderAutoPerformService;
import com.fish.vo.Passport;

/**
 * 通关产品自动履行服务
 * @author lipengcheng
 *
 */
public class OrderAutoPerformServiceImpl implements OrderAutoPerformService{
	private PassCodeDAO passCodeDAO;
	private PassPortCodeDAO passPortCodeDAO;
	private UsedCodeProcessor usedCodeProcessor;
	private Log log = LogFactory.getLog(OrderAutoPerformServiceImpl.class);
	/**
	 * 通关产品订单自动履行方法
	 */
	public void autoPerform() {
		List<PassCode> passCodeList = passCodeDAO.selectAutoPerform();
		if(passCodeList!=null && !passCodeList.isEmpty()){
			doPerform(passCodeList);
		}
	}
	
	/**
	 * 执行自动履行
	 * @param passCodeList
	 */
	private void doPerform(List<PassCode> passCodeList) {
		for (PassCode passCode : passCodeList) {
			if (passCode != null) {
				List<PassPortCode> passPortList = this.passPortCodeDAO.queryProviderByCode(passCode.getCodeId());
				passCode.setPassPortList(passPortList);
				OrderPerformProcessor orderPerform = (OrderPerformProcessor) ProcessorFactory.create(passCode);
				if (orderPerform != null) {
					Passport passport = orderPerform.perform(passCode);
					if (passport != null) {
						String targetId = passCode.getPassPortList().get(0).getTargetId();
						passport.setPortId(targetId);
						passport.setOutPortId(targetId.toString());
						passport.setSerialno(passCode.getSerialNo());
						String code = usedCodeProcessor.update(passport);
						log.info("passCode: " + passCode.getCodeId() + "AutoUpdatePerformStatus: " + code);
					}
				}
			}
		}
	}
	
	public void setPassCodeDAO(PassCodeDAO passCodeDAO) {
		this.passCodeDAO = passCodeDAO;
	}

	public void setPassPortCodeDAO(PassPortCodeDAO passPortCodeDAO) {
		this.passPortCodeDAO = passPortCodeDAO;
	}

	public void setUsedCodeProcessor(UsedCodeProcessor usedCodeProcessor) {
		this.usedCodeProcessor = usedCodeProcessor;
	}
	
}
